package com.sunlands.zlcx.usercenter.repository;

import com.sunlands.zlcx.usercenter.domain.VipUserDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.LockModeType;
import java.util.List;

/**
 * @author shixiaopeng
 */
@Repository
public interface VipUserRepository extends JpaRepository<VipUserDO, Long>, JpaSpecificationExecutor<VipUserDO> {

    List<VipUserDO> findAllByUserIdOrderByLevelDesc(Long userId);

    VipUserDO findFirstByUserIdAndLevel(Long userId, Integer level);

    /**
     * 跟新vip时，使用此方法，对数据行进行加锁，防止出现问题
     * @param id id
     * @return VipUserDO
     */
    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    VipUserDO findById(Long id);

    @Query(value = "select  t.id from  tz_user t where t.vip_status=1 and not EXISTS" +
            "(select * from tz_vip_user s where s.user_id = t.id and s.status=1 and s.level!=150 and s.level!=300 ) ", nativeQuery = true)
    List<Long> findAllExpireUser();
}
